<template>
  <div class="select-room">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>宿舍选择</span>
        </div>
      </template>
      
      <!-- 当前宿舍信息 -->
      <div v-if="currentRoom.dormitory" class="current-room">
        <el-alert
          title="当前宿舍信息"
          type="success"
          :closable="false"
          show-icon
        >
          <p>宿舍楼：{{ currentRoom.dormitory }}</p>
          <p>房间号：{{ currentRoom.roomNum }}</p>
          <p>床位号：{{ currentRoom.bedNum }}</p>
        </el-alert>
      </div>
      
      <!-- 选择区域 -->
      <div class="selection-area">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="selection-step">
              <h3>1. 选择宿舍楼</h3>
              <el-select
                v-model="selectedDormitory"
                placeholder="请选择宿舍楼"
                @change="onDormitoryChange"
                style="width: 100%"
              >
                <el-option
                  v-for="dormitory in dormitories"
                  :key="dormitory.dormitory"
                  :label="dormitory.dormitory"
                  :value="dormitory.dormitory"
                />
              </el-select>
            </div>
          </el-col>
          
          <el-col :span="8">
            <div class="selection-step">
              <h3>2. 选择楼层</h3>
              <el-select
                v-model="selectedFloor"
                placeholder="请选择楼层"
                @change="onFloorChange"
                :disabled="!selectedDormitory"
                style="width: 100%"
              >
                <el-option
                  v-for="floor in floors"
                  :key="floor"
                  :label="`${floor}楼`"
                  :value="floor"
                />
              </el-select>
            </div>
          </el-col>
          
          <el-col :span="8">
            <div class="selection-step">
              <h3>3. 选择房间</h3>
              <el-select
                v-model="selectedRoom"
                placeholder="请选择房间"
                @change="onRoomChange"
                :disabled="!selectedFloor"
                style="width: 100%"
              >
                <el-option
                  v-for="room in availableRooms"
                  :key="room.roomName"
                  :label="room.roomName"
                  :value="room"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 床位选择 -->
      <div v-if="selectedRoom" class="bed-selection">
        <h3>4. 选择床位</h3>
        <div class="bed-grid">
          <div
            v-for="bed in bedNumbers"
            :key="bed"
            class="bed-item"
            :class="{ 
              'selected': selectedBed === bed,
              'occupied': occupiedBeds.includes(bed)
            }"
            @click="selectBed(bed)"
          >
            <el-icon><Bed /></el-icon>
            <span>{{ bed }}号床</span>
            <div v-if="occupiedBeds.includes(bed)" class="occupied-label">已占用</div>
          </div>
        </div>
      </div>
      
      <!-- 确认按钮 -->
      <div v-if="selectedBed && !occupiedBeds.includes(selectedBed)" class="confirm-section">
        <el-button
          type="primary"
          size="large"
          @click="confirmSelection"
          :loading="submitting"
        >
          确认选择
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../../utils/request'

const dormitories = ref([])
const availableRooms = ref([])
const currentRoom = ref({})
const occupiedBeds = ref([])

const selectedDormitory = ref('')
const selectedFloor = ref('')
const selectedRoom = ref(null)
const selectedBed = ref('')
const submitting = ref(false)

const floors = computed(() => {
  if (!selectedDormitory.value) return []
  const dormitory = dormitories.value.find(d => d.dormitory === selectedDormitory.value)
  return dormitory ? Array.from({length: dormitory.floors}, (_, i) => i + 1) : []
})

const bedNumbers = computed(() => {
  if (!selectedRoom.value) return []
  return Array.from({length: selectedRoom.value.roomSize}, (_, i) => i + 1)
})

const loadCurrentRoom = async () => {
  try {
    const response = await request.get('/api/student/profile')
    if (response.data.code === 200 && response.data.data) {
      currentRoom.value = response.data.data
    }
  } catch (error) {
    console.error('获取当前宿舍信息失败:', error)
  }
}

const loadDormitories = async () => {
  try {
    const response = await request.get('/api/dormitory/list')
    if (response.data.code === 200) {
      dormitories.value = response.data.data
    }
  } catch (error) {
    ElMessage.error('获取宿舍楼信息失败')
  }
}

const onDormitoryChange = () => {
  selectedFloor.value = ''
  selectedRoom.value = null
  selectedBed.value = ''
  availableRooms.value = []
}

const onFloorChange = async () => {
  selectedRoom.value = null
  selectedBed.value = ''
  
  if (!selectedDormitory.value || !selectedFloor.value) return
  
  try {
    const response = await request.get('/api/room/available', {
      params: {
        dormitory: selectedDormitory.value,
        floor: selectedFloor.value
      }
    })
    if (response.data.code === 200) {
      availableRooms.value = response.data.data
    }
  } catch (error) {
    ElMessage.error('获取房间信息失败')
  }
}

const onRoomChange = async () => {
  selectedBed.value = ''
  occupiedBeds.value = []
  
  if (!selectedRoom.value) return
  
  // 获取已占用床位
  try {
    const response = await request.get('/api/student/list')
    if (response.data.code === 200) {
      const students = response.data.data
      occupiedBeds.value = students
        .filter(student => 
          student.dormitory === selectedRoom.value.dormitory &&
          student.roomNum === selectedRoom.value.roomNum.toString()
        )
        .map(student => parseInt(student.bedNum))
        .filter(bed => !isNaN(bed))
    }
  } catch (error) {
    console.error('获取床位占用信息失败:', error)
  }
}

const selectBed = (bedNumber) => {
  if (occupiedBeds.value.includes(bedNumber)) {
    ElMessage.warning('该床位已被占用')
    return
  }
  selectedBed.value = bedNumber
}

const confirmSelection = async () => {
  try {
    await ElMessageBox.confirm(
      `确定选择 ${selectedRoom.value.dormitory} ${selectedRoom.value.roomNum} 房间的 ${selectedBed.value} 号床位吗？`,
      '确认选择',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    submitting.value = true
    
    const response = await request.post('/api/student/select-room', {
      dormitory: selectedRoom.value.dormitory,
      roomNum: selectedRoom.value.roomNum.toString(),
      bedNum: selectedBed.value.toString()
    })
    
    if (response.data.code === 200) {
      ElMessage.success('选择宿舍成功')
      await loadCurrentRoom()
      
      // 清空选择
      selectedDormitory.value = ''
      selectedFloor.value = ''
      selectedRoom.value = null
      selectedBed.value = ''
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '选择宿舍失败')
    }
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  loadCurrentRoom()
  loadDormitories()
})
</script>

<style scoped>
.select-room {
  padding: 20px;
}

.current-room {
  margin-bottom: 30px;
}

.selection-area {
  margin-bottom: 30px;
}

.selection-step {
  margin-bottom: 20px;
}

.selection-step h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
}

.bed-selection {
  margin-bottom: 30px;
}

.bed-selection h3 {
  margin-bottom: 20px;
  color: #303133;
  font-size: 16px;
}

.bed-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 15px;
}

.bed-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.bed-item:hover:not(.occupied) {
  border-color: #409EFF;
  background-color: #f0f9ff;
}

.bed-item.selected {
  border-color: #409EFF;
  background-color: #409EFF;
  color: white;
}

.bed-item.occupied {
  border-color: #f56c6c;
  background-color: #fef0f0;
  cursor: not-allowed;
  opacity: 0.6;
}

.bed-item .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.occupied-label {
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: #f56c6c;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 4px;
}

.confirm-section {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}
</style> 